package org.ds.blog.controller;

import org.ds.blog.model.Article;
import org.ds.blog.model.Response;
import org.ds.blog.service.ArticleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
@RequestMapping(value = "/articles",produces = "application/json")
public class ArticleController {
    @Resource
    ArticleService articleService;

    /**
     *
     * @param state 表示文章的状态，1表示为正常状态，2表示在回收站中，这里传参进来的参数默认值为-2即所有状态的文章都会被查询到
     * @param userId 传入作者ID对作者的文章进行查找
     * @param title 传入标题对标题进行模糊查找
     * @return 访问此URL默认为全部文章
     */
    @GetMapping("/all")
    public Response getArticleByTitle(@RequestParam(value = "state",defaultValue = "-2") Integer state,
                                      @RequestParam(value = "userId",defaultValue = "0") Integer userId,
                                      String title){
        return Response.ok().data(articleService.getArticleByState(state,userId,title));
    }

    /**
     *
     * @param articleId 从URL中读取ID对文章详情进行查看
     * @return 返回对应文章
     */
    @GetMapping("/{id}")
    public Response getArticleDetails(@PathVariable("id") Integer articleId){
        return Response.ok().data(articleService.getArticleById(articleId));
    }

    /**
     *
     * @param article 传入一个普通的文章对象表单进行新增操作
     * @return 返回新增结果
     */
    @PostMapping("/")
    public Response postArticle(Article article){
        System.out.println(article.toString());
        int result=articleService.addArticle(article);
        if(result==1){
            return Response.ok().data("增加成功");
        }else {
            return Response.fail().data("增加失败");
        }
    }

    /**
     *
     * @param articleId 传入文章ID
     * @param state 传入文章的状态，如果文章状态为2则直接全部删除，否则将文章放入回收站
     * @return 返回删除结果
     */
    @PutMapping("/dustbin")
    public Response deleteArticle(Integer []articleId,Integer state){
        if(articleService.deleteArticlesByState(articleId,state)==articleId.length){
            return Response.ok().data("删除成功");
        }else{
            return Response.fail().data("删除失败");
        }
    }

    /**
     *
     * @param articleId 传入文章ID
     * @return 返回恢复结果
     */
    @PutMapping("/restore")
    public Response restoreArticles(Integer articleId){
        if(articleService.restoreArticleById(articleId)==1){
            return Response.ok().data("恢复成功");
        }else {
            return Response.fail().data("恢复失败");
        }
    }




}
